package com.oeaide.workflow.aprendizaje;
import java.util.ArrayList;
import java.util.List;

import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.db.GraphSession;
import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.exe.Token;
import org.jbpm.taskmgmt.exe.TaskInstance;

import com.oeaide.workflow.aprendizaje.beans.*;


public class SolicitarActividadesProcessManager
{
	   static JbpmConfiguration jbpmConfiguration = null;
	   static SolicitarActividadesProcessManager __instance = null;

	   private SolicitarActividadesProcessManager() 
	    {
	        startConfiguration();
	    }

	   public static SolicitarActividadesProcessManager getInstance() {
	        if (__instance == null) {
	            __instance = new SolicitarActividadesProcessManager();
	        }
	        return __instance;
	    }
	    

	    static void startConfiguration() {
	        jbpmConfiguration = JbpmConfiguration.parseXmlString(
	                "<jbpm-configuration>" +
	                "  <jbpm-context>" +
	                "    <service name='persistence' " +
	                "             factory='org.jbpm.persistence.db.DbPersistenceServiceFactory' />" +
	                "    <service name='tx' " +
	                "	            factory='org.jbpm.tx.TxServiceFactory' />" +
	                "  </jbpm-context>" +
	                "  <string name='resource.hibernate.cfg.xml' " +
	                "          value='hibernate.cfg.xml' />" +
	                "  <string name='resource.business.calendar' " +
	                "          value='org/jbpm/calendar/jbpm.business.calendar.properties' />" +
	                "  <string name='resource.default.modules' " +
	                "          value='org/jbpm/graph/def/jbpm.default.modules.properties' />" +
	                "  <string name='resource.converter' " +
	                "          value='org/jbpm/db/hibernate/jbpm.converter.properties' />" +
	                "  <string name='resource.action.types' " +
	                "          value='org/jbpm/graph/action/action.types.xml' />" +
	                "  <string name='resource.node.types' " +
	                "          value='org/jbpm/graph/node/node.types.xml' />" +
	                "  <string name='resource.varmapping' " +
	                "          value='org/jbpm/context/exe/jbpm.varmapping.xml' />" +
	                "</jbpm-configuration>");
	
	    }
	    
	public void RegistrarSolicitud(SolicitudActividadBean solicitud)
	{
		 
		        JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
		        try {
		            GraphSession graphSession = jbpmContext.getGraphSession();
		            ProcessDefinition processDefinition =
		                    graphSession.findLatestProcessDefinition("AprobarSolicitud");
		            ProcessInstance processInstance = new ProcessInstance(processDefinition);

		            ContextInstance contextInstance = processInstance.getContextInstance();
		            contextInstance.setVariable("nombre", solicitud.getNombre());
		            contextInstance.setVariable("universidad", solicitud.getUniversidad());
		            contextInstance.setVariable("objetivos", solicitud.getObjetivos());
		            contextInstance.setVariable("fechaInicio", solicitud.getFechaInicio());
		            contextInstance.setVariable("fechaFin", solicitud.getFechaFin());
		            contextInstance.setVariable("especialidad", solicitud.getEspecialidad());
		            contextInstance.setVariable("horasDictado", solicitud.getHorasDictado());
		            contextInstance.setVariable("recursos", solicitud.getRecursos());
		            contextInstance.setVariable("id",String.valueOf(processInstance.getId()));
		            
		            Token token = processInstance.getRootToken();
		            token.signal();
		            token.signal();
		            jbpmContext.save(processInstance);
		        } finally {
		            jbpmContext.close();
		        }
	}

	 public List<SolicitudActividadBean> SolicitudesPendientes()
	 {
	        JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
	        List<SolicitudActividadBean> solicitudes = new ArrayList<SolicitudActividadBean>();
	        try {
	            GraphSession graphSession = jbpmContext.getGraphSession();
	            ProcessDefinition processDefinition = graphSession.findLatestProcessDefinition("AprobarSolicitud");
	            List processInstances = graphSession.findProcessInstances(processDefinition.getId());
	            for (int i = 0; i < processInstances.size(); i++) 
	            {
	            	
	                ProcessInstance processInstance = (ProcessInstance) processInstances.get(i);
	                ContextInstance contextInstance = processInstance.getContextInstance();
	                System.out.println("ESTADO: " + processInstance.getRootToken().getNode().getName());
	                if (!processInstance.getRootToken().getNode().getName().equals("Fin"))
	                {
	                	SolicitudActividadBean nuevo = new SolicitudActividadBean();
	 	                nuevo.setId(String.valueOf(processInstance.getId()));
	 	                System.out.println(nuevo.getId());
	 	                nuevo.setUniversidad(contextInstance.getVariable("universidad").toString());
	 	                System.out.println(nuevo.getUniversidad());
	 	                nuevo.setRecursos(contextInstance.getVariable("recursos").toString());
	 	                nuevo.setFechaFin(contextInstance.getVariable("fechaFin").toString());
	 	                nuevo.setFechaInicio(contextInstance.getVariable("fechaInicio").toString());
	 	                nuevo.setEspecialidad(contextInstance.getVariable("especialidad").toString());	
	 	                nuevo.setHorasDictado(Integer.parseInt(contextInstance.getVariable("horasDictado").toString()));
	 	                nuevo.setNombre(contextInstance.getVariable("nombre").toString());
	 	                nuevo.setObjetivos(contextInstance.getVariable("objetivos").toString());
	 	                solicitudes.add(nuevo);
	                }
	               
	            }
	        }catch(Exception ex)
	        {	
	        	System.out.print(ex.getMessage());
	        } 
	        finally {
	            jbpmContext.close();
	        }
	        return solicitudes;
	    }

	 
	 public void AprobarSolicitud(SolicitudActividadBean solicitud) 
	 {
		 JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
	        try {
	            GraphSession graphSession = jbpmContext.getGraphSession();
	            
	            ProcessDefinition processDefinition =
	                    graphSession.findLatestProcessDefinition("AprobarSolicitud");
	            List processInstances = graphSession.findProcessInstances(processDefinition.getId());
	            
	          
	            for (int i = 0; i < processInstances.size(); i++) 
	            {
	                ProcessInstance processInstance = (ProcessInstance) processInstances.get(i);
	                ContextInstance contextInstance = processInstance.getContextInstance();
	                
	                if (solicitud.getId().equals(String.valueOf(processInstance.getId())))
	                {
	                	List<TaskInstance> tasks=jbpmContext.getTaskMgmtSession().findTaskInstancesByProcessInstance(processInstance);
	                	for(TaskInstance ti : tasks){
	            			System.out.println("TaskInstance ID: "+ti.getId()+" - Name: "+ti.getName()+ " - Creada: " +ti.getCreate());
	            		}
	                	
	            		
	            		if(tasks.size() > 0)
	            		{
	            			System.out.println("ESTADO: " + processInstance.getRootToken().getNode().getName());
	            			TaskInstance elegirTarea=tasks.get(1);
	            			System.out.println("Encontre una tarea = "+elegirTarea.getName());
	            			elegirTarea.start();
	            			System.out.println("la variable Aprueba tiene el valor = "+elegirTarea.getVariable("aprobar"));
	            			elegirTarea.setVariable("aprobar", "aprueba");
	            			System.out.println("la variable Aprueba tiene el valor = "+elegirTarea.getVariable("aprobar"));
	            			elegirTarea.end();
	            			
	            			
	            			Token token = processInstance.getRootToken();
	    		            token.signal();
	    		            
	            		  }
	                }
	                jbpmContext.save(processInstance);
	            }    
	        }catch(Exception ex)
	        {	
	        	System.out.print(ex.getMessage());
	        } 
	        finally 
	        {
	            jbpmContext.close();
	        
	        }
	 }
	

	}


